package com.by.wx.process.msg;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.by.wx.mapper.MonitorTaskMapper;
import com.by.wx.model.msg.MessageDto;
import com.by.wx.model.script.MonitorTask;
import com.by.wx.utils.PushMsgUtils;
import com.by.wx.utils.TaskUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @Author 陈子杰
 * @Description 消息处理类
 * @Version 1.0.0
 * @Date 2025/2/12 18:42
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FlightSubscriptionProcessServ {
    private final MonitorTaskMapper monitorTaskMapper;
    private final PushMsgUtils pushMsgUtils;

    public void processMsg(MessageDto messageDto) {
        String content = messageDto.getContent();
        String[] lines = content.split("\n");
        // 第一行是type
        String type = lines[1];
        // 添加监控：只监控余票减少
        // 航班订阅：只要余票有变动就会报警
        if (!StrUtil.equals(type, "添加监控") || StrUtil.equals(type, "航班订阅")) {
            return;
        }
        String date = lines[2].split("：")[1];
        String departure = lines[3].split("：")[1];
        String arrival = lines[4].split("：")[1];
        String flightNo = lines[5].split("：")[1];
        String cabin = lines[6].split("：")[1];
        // 生成任务ID
        String taskId = TaskUtils.generateTaskId(departure, arrival, date, flightNo);
        JSONObject chatroomInfo = pushMsgUtils.getChatroomInfo(messageDto.getFromWxId());
        JSONObject data = chatroomInfo.getJSONObject("data");
        String nickName = data.getString("nickName");
        MonitorTask task = MonitorTask.builder()
                .taskId(taskId)
                .type(1)
                .chatroomId(messageDto.getFromWxId())
                .nickName(nickName)
                .date(date)
                .departure(departure)
                .arrival(arrival)
                .flightNo(flightNo)
                .cabin(cabin)
                .createTime(LocalDateTime.now())
                .expirationTime(LocalDate.now().plusDays(16).toString())
                .build();
        if (type.equals("添加监控")) {
            task.setType(1);
        } else if (type.equals("航班订阅")) {
            task.setType(2);
        }
        monitorTaskMapper.insert(task);
        pushMsgUtils.textMsg(messageDto.getFromWxId(), String.format("任务订阅成功：%s", taskId));
    }
}
